package comm.util;

import com.fasterxml.jackson.core.type.TypeReference;
import comm.TokenContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.misc.BASE64Encoder;

/**
 * 基础接口，主要是获取accessToken等授权信息的，用的比较多
 *
 * @Author: junes 2022/9/16 18:41
 * @Update: junes 2022/9/16 18:41
 */
public class HdOpenUtilBase {
    // todo 方便工具打印日志，自行更换
    public static final Logger LOGGER = LogManager.getLogger(HdOpenUtilBase.class);

    // 授权地址
    final static String AUTH_URL = "https://openauth-hd.fkw.com";
    // 请求接口服务地址
    final static String API_URL = "https://open-hd.fkw.com";

    // todo clientId和clientSecret请到凡科互动开放平台登录查看
    final static String CLIENT_ID = "fk-hd-open-client-173";
    final static String CLIENT_SECRET = "b2e4e848ba08b37b3f53d5478c21ef31";

    /**
     * token数据转对象
     *
     * @Author: junes 2022/9/16 17:19
     * @Update: junes 2022/9/16 17:19
     */
    private static TokenContext getTokenContext(String resultJson) {
        TypeReference typeReference = new TypeReference<TokenContext>() {
        };

        TokenContext tokenContext = (TokenContext) JsonUtils.nativeRead(resultJson, typeReference);
        if (tokenContext.getAccessToken() == null || tokenContext.getAccessToken().isEmpty()) {
            // 报错信息
            LOGGER.error(resultJson);
            return null;
        }

        return tokenContext;
    }

    /**
     * Basic Auth
     *
     * @Author: junes 2022/9/16 17:26
     * @Update: junes 2022/9/16 17:26
     */
    protected static String getBasicAuth() throws Exception {
        BASE64Encoder encoder = new BASE64Encoder();
        String clientContent = CLIENT_ID + ":" + CLIENT_SECRET;
        return "Basic " + encoder.encode(clientContent.getBytes("UTF-8"));
    }

    /**
     * 获取partner_access_token
     * 调用接口的时候需要用到，建议缓存起来使用
     *
     * @Author: junes 2022/9/14 19:54
     * @Update: junes 2022/9/14 19:54
     */
    public static TokenContext getAccessToken() throws Exception {
        String url = AUTH_URL + "/oauth/partner/token";
        OkHttpUtils httpUtils = OkHttpUtils.builder()
                .url(url)
                .addHeader("Authorization", getBasicAuth())
                .addParam("auth_type", "partner_client_credential");

        String resultJson = httpUtils.post(false).sync();
        return getTokenContext(resultJson);
    }

    /**
     * 获取code 获取access_token需要 （旧） 不推荐使用此接口获取PartnerAccessToken
     *
     * @Author: junes 2022/9/14 19:54
     * @Update: junes 2022/9/14 19:54
     */
    @Deprecated
    public static String getCode(String state, String auth_uid, String auth_uid_extra, String auth_uid_name, String auth_uid_head) {
        String url = AUTH_URL + "/oauth/authorize";

        // redirect_uri 需要填写再凡科互动开放平台里面。
        String redirect_uri = "https://mock.apifox.cn/m1/1601336-0-f8ec4cd1/oauth/authorize?apifoxToken=IxRgufC2fFC5rEVVAmDlvqwPGSExvtHv";

        OkHttpUtils httpUtils = OkHttpUtils.builder()
                .url(url)
                .addParam("client_id", CLIENT_ID)
                .addParam("redirect_uri", redirect_uri)
                .addParam("response_type", "code")
                .addParam("scope", "all")
                .addParam("state", state)
                .addParam("auth_uid", auth_uid)
                .addParam("auth_uid_extra", auth_uid_extra)
                .addParam("auth_uid_name", auth_uid_name)
                .addParam("auth_uid_head", auth_uid_head);

        return httpUtils.get().sync();
    }

    /**
     * 基础使用需要uid，其他参数可以自行决定扩展 （旧） 不推荐使用此接口获取PartnerAccessToken
     *
     * @Author: junes 2022/9/16 17:27
     * @Update: junes 2022/9/16 17:27
     */
    @Deprecated
    public static String getCode(String auth_uid) {
        return getCode("", auth_uid, "", "", "");
    }

    /**
     * 通过code换取access_token（旧） 不推荐使用此接口获取
     * 网页授权的时候需要用来拼接活动链接
     *
     * @Author: junes 2022/9/16 16:19
     * @Update: junes 2022/9/16 16:19
     */
    @Deprecated
    public static TokenContext getPartnerAccessToken(String code) throws Exception {
        String url = AUTH_URL + "/oauth/token";

        // redirect_uri 需要填写再凡科互动开放平台里面。
        String redirect_uri = "https://mock.apifox.cn/m1/1601336-0-f8ec4cd1/oauth/authorize?apifoxToken=IxRgufC2fFC5rEVVAmDlvqwPGSExvtHv";

        OkHttpUtils httpUtils = OkHttpUtils.builder()
                .url(url)
                .addHeader("Authorization", getBasicAuth())
                .addParam("grant_type", "authorization_code")
                .addParam("redirect_uri", redirect_uri)
                .addParam("code", code);

        String resultJson = httpUtils.post(false).sync();
        return getTokenContext(resultJson);
    }


    /**
     *  服务器直接获取partner_access_token，推荐使用此方法获取
     *  文档https://www.yuque.com/fid66z/sn2hbe/awr1guucckpc69mv

     * @Author: maxchen 2023/8/1 12:19
     * @Update: maxchen 2023/8/1 12:19
     */
    public static TokenContext getPartnerAccessToken_direct(String auth_uid, String auth_uid_extra, String auth_uid_name,
                                                            String auth_uid_head) throws Exception {
        String url = AUTH_URL + "/oauth/token";
        OkHttpUtils httpUtils = OkHttpUtils.builder()
                .url(url)
                .addHeader("Authorization", getBasicAuth())
                .addParam("grant_type", "authorization_direct")
                .addParam("auth_uid", auth_uid)
                .addParam("auth_uid_extra", auth_uid_extra)
                .addParam("auth_uid_name", auth_uid_name)
                .addParam("auth_uid_head", auth_uid_head);

        String resultJson = httpUtils.post(false).sync();
        return getTokenContext(resultJson);
    }



}
